package com.michael.study.library.utils

import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import androidx.core.app.NotificationManagerCompat

object SystemUtil {

    fun dp2px(context: Context, dp: Int): Int {
        val scale = context.resources.displayMetrics.density
        return (dp * scale + 0.5f).toInt()
    }

    fun px2dp(context: Context, dp: Int): Int {
        val scale = context.resources.displayMetrics.density
        return (dp / scale + 0.5f).toInt()
    }

    /**
     * 获取 AndroidManifest.xml meta 的 value 值
     */
    fun getMeta(context: Context,name:String): String? {
        val appInfo: ApplicationInfo
        try {
            appInfo = context.packageManager
                .getApplicationInfo(context.packageName, PackageManager.GET_META_DATA)
            val bundle = appInfo.metaData
            return bundle.getString(name, null)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }

    /**
     * 获取状态栏高度
     */
    fun getStatusBarByResId(context: Context): Int {
        var height = 0
        //获取状态栏资源id
        val resourceId =
            context.resources.getIdentifier("status_bar_height", "dimen", "android")
        if (resourceId > 0) {
            try {
                height = context.resources.getDimensionPixelSize(resourceId)
            } catch (e: java.lang.Exception) {
            }
        }
        return if (height <= 0) {
            dp2px(context, 25)
        } else height
    }

    /**
     * 判断通知栏是否开启
     */
    fun isNotificationEnabled(context: Context?): Boolean {
        var isOpened = false
         try {
             isOpened =     NotificationManagerCompat.from(context!!).areNotificationsEnabled()
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
        return isOpened
    }

    /**
     * 跳转通知栏
     */
    fun gotoSetting(context: Context) {
        val intent = Intent()
        if (Build.VERSION.SDK_INT >= 26) {
            // android 8.0引导
            intent.action = "android.settings.APP_NOTIFICATION_SETTINGS"
            intent.putExtra("android.provider.extra.APP_PACKAGE", context.packageName)
        } else if (Build.VERSION.SDK_INT >= 21) {
            // android 5.0-7.0
            intent.action = "android.settings.APP_NOTIFICATION_SETTINGS"
            intent.putExtra("app_package", context.packageName)
            intent.putExtra("app_uid", context.applicationInfo.uid)
        } else {
            // 其他
            intent.action = "android.settings.APPLICATION_DETAILS_SETTINGS"
            intent.data = Uri.fromParts("package", context.packageName, null)
        }
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        context.startActivity(intent)
    }

}